package com.harveyspace.aes.social.instagram;

import com.harveyspace.aes.core.utils.HttpUtil;
import com.harveyspace.aes.core.utils.JsonUtil;
import com.harveyspace.aes.social.Oauth;
import com.harveyspace.aes.social.SocialConfig;
import com.harveyspace.aes.social.exception.SocialException;
import com.harveyspace.aes.social.pojo.AccessTokenInfo;
import com.harveyspace.aes.social.pojo.SocialiteUserInfo;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @Author <a href="harveyer@163.com">harvey</a>
 * @date 2018/2/9
 */
public class OauthInstagram extends Oauth {

    private final String TOKEN_URL = "https://api.instagram.com/oauth/access_token";
    
    private InstagramUserInfo instagramUserInfo;
    
    /**
     * @param socialConfig 配置信息
     */
    public OauthInstagram(SocialConfig socialConfig) {
        super(socialConfig);
        AUTH_URL = "https://api.instagram.com/oauth/authorize";
    }
    
    /**
     * 获取授权url
     *
     * @param state OAuth2.0标准协议建议，利用state参数来防止CSRF攻击
     * @return String
     */
    @Override
    public String getAuthorizeUrl(String state) {
        return super.getAuthorizeUrl(state);
    }

    /**
     * 获取token 返回的是JSON 解析获取到Token以及OpenId
     * 
     * @param code 使用code换取token
     * @return String 返回类型
     * @throws SocialException 获取access token 异常
     */
    @Override
    public AccessTokenInfo getAccessToken(String code) throws SocialException {

        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        params.put("client_id", socialConfig.getClientId());
        params.put("client_secret", socialConfig.getClientSecret());
        params.put("redirect_uri", socialConfig.getRedirectUri());

        String result;
        try {
            result = HttpUtil.postString(TOKEN_URL, 1, params);
        } catch (IOException e) {

            String errorMessage = String.format("通过 code[%s] 获取 access token异常", code);
            logger.error(errorMessage, e);
            throw new SocialException(errorMessage);
        }

        Map<String, Object> responseMap = JsonUtil.toMap(result);

        if(StringUtils.isNotBlank(MapUtils.getString(responseMap, "errcode"))){

            String errorCode = MapUtils.getString(responseMap, "errcode");
            String errorMessage = MapUtils.getString(responseMap, "errmsg");

            throw new SocialException(String.format("通过 code[%s] 获取 access token异常:%s[%s]", code, errorMessage, errorCode));
        }

        instagramUserInfo = JsonUtil.toObject(result, InstagramUserInfo.class);

        return JsonUtil.toObject(result, AccessTokenInfo.class);
    }

    @Override
    public SocialiteUserInfo getSocialUserInfo(AccessTokenInfo accessTokenInfo) {

        SocialiteUserInfo socialiteUserInfo = new SocialiteUserInfo();

        socialiteUserInfo.setUnionId(accessTokenInfo.getUnionId());
        socialiteUserInfo.setOpenId(accessTokenInfo.getOpenId());
        socialiteUserInfo.setUnionId(instagramUserInfo.getId());
        socialiteUserInfo.setAvatar(instagramUserInfo.getProfilePicture());
        socialiteUserInfo.setName(instagramUserInfo.getFullName());
        socialiteUserInfo.setNickName(instagramUserInfo.getUsername());

        return socialiteUserInfo;
    }
}
